<template>
  <div class="order-create">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>创建订单</span>
        </div>
      </template>
      <el-form
        ref="orderFormRef"
        :model="orderForm"
        :rules="rules"
        label-width="120px"
        class="create-form"
      >
        <el-form-item label="客户名称" prop="customerId">
          <el-input
            v-model="orderForm.customerName"
            placeholder="请输入客户名称"
            readonly
            @click="openCustomerSelect"
          />
        </el-form-item>

        <el-form-item label="订单类型" prop="orderSubType">
          <el-select v-model="orderForm.orderSubType" placeholder="请选择订单类型">
            <el-option label="案件委托" :value="1" />
            <el-option label="法务订单" :value="2" />
            <el-option label="法务专项" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="订单金额" prop="totalAmount">
          <el-input-number
            v-model="orderForm.totalAmount"
            :min="0"
            :precision="2"
            placeholder="请输入订单金额"
          />
        </el-form-item>

        <el-form-item label="签约人" prop="signerName">
          <el-input v-model="orderForm.signerName" placeholder="请输入签约人姓名" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="orderForm.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="合同文件">
          <el-upload
            ref="uploadRef"
            action=""
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="orderForm.contract_files"
            multiple
            accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
            list-type="picture-card"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img
                  v-if="file.url && isImage(file.name)"
                  :src="file.url"
                  alt="文件预览"
                  class="el-upload-list__item-thumbnail"
                />
                <el-icon v-else class="el-upload-list__item-icon"><Document /></el-icon>
                <span class="el-upload-list__item-name">{{ file.name }}</span>
                <el-button type="text" size="small" @click.stop="previewFile(file)">预览</el-button>
                <el-button type="text" size="small" @click.stop="removeFile(file)">删除</el-button>
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 客户选择对话框 -->
    <el-dialog
      v-model="customerDialogVisible"
      title="选择客户"
      width="70%"
      @closed="handleDialogClose"
    >
      <!-- 这里可以放置客户选择组件或表格 -->
      <div class="customer-select">
        <el-input
          v-model="customerSearch"
          placeholder="搜索客户名称"
          clearable
          @keyup.enter="searchCustomers"
        />
        <el-button type="primary" @click="searchCustomers">搜索</el-button>

        <el-table :data="customerList" style="width: 100%" @row-click="selectCustomer">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="客户名称" width="200" />
          <el-table-column prop="contact_person" label="联系人" width="120" />
          <el-table-column prop="contact_phone" label="联系电话" width="150" />
          <el-table-column prop="address" label="地址" show-overflow-tooltip />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox, ElUpload, UploadUserFile } from 'element-plus'
  import { Plus, Document } from '@element-plus/icons-vue'

  const router = useRouter()
  const orderFormRef = ref()
  const uploadRef = ref<InstanceType<typeof ElUpload>>()
  const customerDialogVisible = ref(false)
  const customerSearch = ref('')
  // 定义客户类型接口
  interface Customer {
    id: number
    name: string
    contact_person: string
    contact_phone: string
    address: string
  }

  const customerList = ref<Customer[]>([])

  // 订单表单数据
  const orderForm = reactive({
    customerId: '',
    customerName: '',
    orderSubType: '',
    totalAmount: 0,
    signerName: '',
    remark: '',
    contract_files: [] as UploadUserFile[],
  })

  // 表单验证规则
  const rules = {
    customerId: [{ required: true, message: '请选择客户', trigger: 'blur' }],
    orderSubType: [{ required: true, message: '请选择订单类型', trigger: 'change' }],
    totalAmount: [
      { required: true, message: '请输入订单金额', trigger: 'blur' },
      { type: 'number', min: 0, message: '订单金额不能为负数', trigger: 'blur' },
    ],
    signerName: [{ required: true, message: '请输入签约人姓名', trigger: 'blur' }],
  }

  // 打开客户选择对话框
  const openCustomerSelect = () => {
    customerDialogVisible.value = true
    // 初始化加载客户列表
    searchCustomers()
  }

  // 搜索客户
  const searchCustomers = async () => {
    try {
      // 这里应该调用API获取客户列表
      // const { getCustomerList } = await import('@/api/customer')
      // const res = await getCustomerList({ name: customerSearch.value, page: 1, limit: 50 })

      // 模拟数据
      customerList.value = [
        {
          id: 1,
          name: '测试客户1',
          contact_person: '张三',
          contact_phone: '13800138001',
          address: '北京市朝阳区',
        },
        {
          id: 2,
          name: '测试客户2',
          contact_person: '李四',
          contact_phone: '13800138002',
          address: '上海市浦东新区',
        },
        {
          id: 3,
          name: '测试客户3',
          contact_person: '王五',
          contact_phone: '13800138003',
          address: '广州市天河区',
        },
      ]
    } catch (error) {
      console.error('获取客户列表失败', error)
      ElMessage.error('获取客户列表失败')
    }
  }

  // 选择客户
  const selectCustomer = (row: Customer) => {
    orderForm.customerId = row.id.toString() // 转换为字符串以匹配表单类型
    orderForm.customerName = row.name
    customerDialogVisible.value = false
  }

  // 判断是否为图片文件
  const isImage = (fileName: string): boolean => {
    const imageTypes = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
    const ext = fileName.toLowerCase().substring(fileName.lastIndexOf('.'))
    return imageTypes.includes(ext)
  }

  // 处理文件选择
  const handleFileChange = (file: any, fileList: any[]) => {
    orderForm.contract_files = fileList
  }

  // 处理文件移除
  const handleFileRemove = (file: any, fileList: any[]) => {
    orderForm.contract_files = fileList
  }

  // 预览文件
  const previewFile = (file: any) => {
    if (file.url) {
      window.open(file.url, '_blank')
    } else if (file.raw) {
      const fileUrl = URL.createObjectURL(file.raw)
      window.open(fileUrl, '_blank')
    }
  }

  // 删除文件
  const removeFile = (file: any) => {
    const index = orderForm.contract_files.findIndex((item: any) => item.uid === file.uid)
    if (index !== -1) {
      orderForm.contract_files.splice(index, 1)
    }
  }

  // 对话框关闭处理
  const handleDialogClose = () => {
    customerSearch.value = ''
    customerList.value = []
  }

  // 提交订单
  const handleSubmit = async () => {
    if (!orderFormRef.value) return

    try {
      await orderFormRef.value.validate()

      // 创建FormData来处理文件上传
      const formData = new FormData()

      // 添加表单字段
      Object.keys(orderForm).forEach(key => {
        if (key !== 'contract_files') {
          formData.append(key, (orderForm as any)[key])
        }
      })

      // 添加合同文件
      orderForm.contract_files.forEach((file: any) => {
        if (file.raw) {
          formData.append('contract_files[]', file.raw, file.name)
        }
      })

      // 这里应该调用API创建订单
      // const { createOrder } = await import('@/api/order')
      // const res = await createOrder(formData)

      // 模拟创建成功
      await ElMessageBox.alert('订单创建成功', '提示', {
        confirmButtonText: '确定',
        callback: () => {
          router.push('/crm/order')
        },
      })
    } catch (error) {
      if (error !== false) {
        console.error('创建订单失败', error)
        ElMessage.error('创建订单失败')
      }
    }
  }

  // 取消
  const handleCancel = () => {
    router.push('/crm/order')
  }
</script>

<style lang="scss" scoped>
  .order-create {
    padding: 20px;

    .create-form {
      max-width: 800px;
    }

    .customer-select {
      padding: 10px 0;

      .el-input {
        width: 300px;
        margin-right: 10px;
        margin-bottom: 20px;
      }

      .el-table {
        margin-top: 20px;
      }
    }
  }
</style>
